import React,{ useEffect, useState } from 'react';
import {
  TabletOutlined,
  InfoCircleOutlined,
  BarChartOutlined,
  CheckOutlined
} from '@ant-design/icons';
import { Modal, Tabs ,Row, Col, message, Spin, Badge, Tag, Button, Progress, Tooltip} from 'antd';
import { DeviceListItem } from '../data';
import { deviceDetail } from '../service'
import moment from 'moment';
import styles from '../index.less';

interface CreateFormProps {
  modalVisible: boolean;
  onCancel: () => void;
  values:DeviceListItem;
}

const { TabPane } = Tabs;

//容量单位转换(kb,mb,gb,tb)
function bytesToSize(type:string,bytes:any) {
  if (bytes === 0) return '0 B';
  let k = 1024,
  sizes = [],
  i = Math.floor(Math.log(bytes) / Math.log(k)),
  n = 3;
  if(type == "bytes"){
    sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
    if(i == 1){
      n = 4;
    }
  }else{
    sizes = ['MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  }
  // let n = 3;
  
  return (bytes / Math.pow(k, i)).toPrecision(n) + ' ' + sizes[i];
}

function formatBytes(a,b){if(0==a)return"0 Bytes";var c=1024,d=b||2,e=["Bytes","KB","MB","GB","TB","PB","EB","ZB","YB"],f=Math.floor(Math.log(a)/Math.log(c));return parseFloat((a/Math.pow(c,f)).toFixed(d))+" "+e[f]}

const DeviceDetail: React.FC<CreateFormProps> = (props) => {
  const { modalVisible, onCancel, values } = props;
  const [deviceValue, setDeviceValue] = useState<DeviceListItem>();
  const [loading, setLoading] = useState<boolean>(false);
  

  useEffect(() => {
    if(modalVisible){
      setLoading(true);
      const controller = new AbortController();
      const signal = controller.signal;
      // new Promise((resolve, reject) => {
        deviceDetail(values.id,signal)
          .then((res) => {
            setLoading(false);
            if(res){
              if (res.code === 200) {
                const data = res.data;
                data.resolution = data.width+"x"+data.height;
                if(data.registerStatus){
                  data.registerStatus = "true";
                }else{
                  data.registerStatus = "false";
                }
  
                if(data.commandSuccess){
                  data.commandSuccess = "success";
                }else{
                  data.commandSuccess = "fail";
                }
                if(data.freeSpace && data.totalSpace){
                  const freeSpace = parseInt(data.freeSpace);
                  const totalSpace = parseInt(data.totalSpace);
                  data.spacePercent = Math.round((totalSpace-freeSpace)/totalSpace*100);
                }else{
                  data.spacePercent = null;
                }
                setDeviceValue(data);
                // resolve(true);
              }else {
                message.error('获取失败，'+res.message);
                // resolve(false);
              }
            }
          })
          .catch((error) => {
            console.log(error)
            message.error('请求失败');
            // reject(error);
          });
          return () => controller.abort();
      // });
    }else{
      setDeviceValue("");
      setLoading(false);
    }
  },[modalVisible]);

  function callback(key) {
    // console.log(key);
  }

  const renderContent = () => {
    return (
      <>
        <Tabs onChange={callback} type="card" className={styles.deviceDetail}>
            <TabPane tab={<span><TabletOutlined />设备信息</span>} key="1" >
              <Row>
                <Col span={12}><strong>设备型号：</strong>{deviceValue?.deviceType?deviceValue.deviceType:"--"}</Col>
                <Col span={12}><strong>设备版本：</strong>{deviceValue?.deviceVersion?deviceValue.deviceVersion:"--"}</Col>
              </Row>
              <Row>
                <Col span={24}><strong>固件版本：</strong><Tooltip placement="topLeft" title={deviceValue?.firmware}>{deviceValue?.firmware?deviceValue.firmware:"--"}</Tooltip></Col>
              </Row>
              <Row>
                <Col span={24}><strong>Webview：</strong><Tooltip placement="topLeft" title={deviceValue?.webView}>{deviceValue?.webView?deviceValue.webView:"--"}</Tooltip></Col>
              </Row>
              <Row>
                <Col span={12}><strong>运行内存：</strong>{deviceValue?.runningMemory?bytesToSize("bytes",deviceValue.runningMemory):"--"}</Col>
                <Col span={12}><strong>板卡型号：</strong>{deviceValue?.boardModel?deviceValue.boardModel:"--"}</Col>
              </Row>
              <Row>
                <Col span={24}><strong>存储空间：</strong>{(deviceValue?.freeSpace&&deviceValue.totalSpace)?
                  <div style={{display:'inline-block'}}>
                    <Progress style={{width:150,verticalAlign:'text-bottom',marginRight:5}} percent={Math.round((parseInt(deviceValue.totalSpace) - parseInt(deviceValue?.freeSpace))/parseInt(deviceValue.totalSpace)*100)} />
                    {"("+formatBytes((parseInt(deviceValue?.totalSpace) - parseInt(deviceValue?.freeSpace))*1024*1024)+'/'+bytesToSize("MB",deviceValue?.totalSpace)+")"}
                  </div>
                  :"--"}
                </Col>
              </Row>
              <Row>
                <Col span={12}><strong>设备时区：</strong>{deviceValue?.timeZone?deviceValue.timeZone:"--"}</Col>
                <Col span={12}><strong>设备时间：</strong>{deviceValue?.deviceTime?moment(deviceValue.deviceTime).format('YYYY-MM-DD HH:mm:ss'):"--"}</Col>
              </Row>
              <Row>
                <Col span={12}><strong>设备IP：</strong>{deviceValue?.ip?deviceValue.ip:"--"}</Col>
                <Col span={12}><strong>MAC地址：</strong>{deviceValue?.mac?deviceValue.mac:"--"}</Col>
              </Row>
            </TabPane>
            <TabPane tab={<span> <InfoCircleOutlined />安装信息</span>} key="2">
              <Row>
                <Col span={12}><strong>设备名称：</strong>{deviceValue?.name?deviceValue.name:"--"}</Col>
                <Col span={12}><strong>注册状态：</strong>{
                  deviceValue?.registerStatus?
                    (deviceValue.registerStatus == "true"?
                      <span><Badge status="success" />已注册</span>:
                      <span><Badge status="default" />未注册</span>
                    ):("--")}
                </Col>
              </Row>
              <Row>
                <Col span={12}><strong>所属机构：</strong>{deviceValue?.orgName?deviceValue.orgName:"--"}</Col>
                <Col span={12}><strong>注册时间：</strong>{deviceValue?.registerDatetime?moment(deviceValue.registerDatetime).format('YYYY-MM-DD HH:mm:ss'):"--"}</Col>
              </Row>
              <Row>
                <Col span={12}><strong>分辨率：</strong>{deviceValue?.resolution?deviceValue.resolution:"--"}</Col>
                <Col span={12}><strong>信发版本：</strong>{deviceValue?.apkVersion?deviceValue.apkVersion:"--"}</Col>
              </Row>
              <Row>
                <Col span={12}><strong>屏幕类型：</strong>{deviceValue?.screenType?deviceValue.screenType:"--"}</Col>
                <Col span={12}><strong>屏显方式：</strong>{deviceValue?.screenDisplay?deviceValue.screenDisplay:"--"}</Col>
              </Row>
              {/* <Row>
                <Col span={24}>安装位置：{deviceValue?.devicePosition?deviceValue.devicePosition:"--"}</Col>
              </Row> */}
            </TabPane>
            <TabPane tab={<span><BarChartOutlined />状态信息</span>} key="3">
            <Row>
                <Col span={12}><strong>在线状态：</strong>{
                  deviceValue?.onlineStatus?
                    (deviceValue.onlineStatus == "ONLINE"?
                      <span><Badge status="success" />在线</span>:
                        (deviceValue.onlineStatus == "OFFLINE"?<span><Badge status="default" />离线</span>:("--"))
                    ):("--")}
                  </Col>
                <Col span={12} title={deviceValue?.nowPlanName?deviceValue.nowPlanName:""}><strong>当前计划：</strong>{deviceValue?.nowPlanName?deviceValue.nowPlanName:"--"}</Col>
              </Row>
              <Row>
                <Col span={12}><strong>播放状态：</strong>{
                  deviceValue?.playStatus?
                    (deviceValue.playStatus == "PLAY"?
                      <span><Badge status="processing" />播放中</span>:
                      (deviceValue.playStatus == "IDLE"?<span><Badge status="default" />空闲</span>:("--"))
                    ):("--")}
                </Col>
                <Col span={12} title={deviceValue?.nowProgramName?deviceValue.nowProgramName:""}><strong>当前节目：</strong>{deviceValue?.nowProgramName?deviceValue.nowProgramName:"--"}</Col>
              </Row>
              <Row>
                <Col span={12}><strong>下载状态：</strong>{
                  deviceValue?.downloadStatus?
                    (deviceValue.downloadStatus=="SUCCESS"?
                      <span><Badge status="success" />下载成功</span>:
                        (deviceValue.downloadStatus == "DOWNLOADING"?
                          <span><Badge status="processing" />正在下载</span>:(deviceValue.downloadStatus == "UNKNOWN"?
                          <span><Badge status="warning" />未知</span>:<span><Badge status="error" />下载失败</span>
                          )
                        )
                    ):("--")}</Col>
                <Col span={12}><strong>默认计划：</strong>{deviceValue?.defaultPlanName?deviceValue.defaultPlanName:"--"}</Col>
              </Row>
              {/* <Row>
                <Col span={12}>设备运行时长：{deviceValue?.devicePosition?deviceValue.devicePosition:"--"}</Col>
                <Col span={12}>关联数据源：{deviceValue?.devicePosition?deviceValue.devicePosition:"--"}</Col>
              </Row> */}
              <Row>
                <Col span={24} style={{display:"flex"}}>
                  <div style={{flex:"none"}}><strong>标签：</strong></div>{deviceValue?.tags && deviceValue?.tags.length>0? 
                  (<ul style={{padding:0,margin:0}}>
                    {deviceValue.tags.map((tag:string,index:number) =>{
                      return (
                        <Tag color="blue" key={index} style={{marginBottom:5}}>
                          {tag}
                        </Tag>
                      );
                    })}
                    </ul>
                  ):("--")}</Col>
              </Row>
              <Row>
                <Col span={12}><strong>心跳：</strong>{
                  deviceValue?.commandSuccess?
                    (deviceValue.commandSuccess == "success"? (<span><Badge status="success" />成功</span>): (<span><Badge status="error" />失败</span>)
                    ):("--")}</Col>
                <Col span={12}><strong>开机时间：</strong>{deviceValue?.powerOnDatetime?moment(deviceValue.powerOnDatetime).format('YYYY-MM-DD HH:mm:ss'):"--"}</Col>
              </Row>
              <Row>
                <Col span={12}><strong>媒体音量：</strong>{deviceValue?.volume?<Progress style={{width:100}} percent={parseInt(deviceValue.volume)} format={() => parseInt(deviceValue.volume)} />:"--"}</Col>
                <Col span={12}><strong>信号强度：</strong>{(deviceValue?.rssi||deviceValue?.rssi == 0)?<Progress style={{width:100}} percent={deviceValue.rssi*25} format={() => deviceValue.rssi==0?"无信号":(deviceValue.rssi==1?"弱":(deviceValue.rssi==2?"中":(deviceValue.rssi==3?"良好":"强")))} steps={4} strokeColor="#52c41a"/>:"--"}</Col>
              </Row>
              <Row>
                <Col span={12}><strong>网络类型：</strong>{deviceValue?.netType?deviceValue.netType:"--"}</Col>
                <Col span={12}><strong>HDMI：</strong>{deviceValue?.hdmi?<label style={{color:'rgb(82 196 26)'}}>已连接<CheckOutlined style={{marginLeft:5}}/></label>:"--"}</Col>
              </Row>
            </TabPane>
          </Tabs>
      </>
    );
  };

  return (
    <Modal
      destroyOnClose
      title="设备详情"
      visible={modalVisible}
      onCancel={onCancel}
      footer={[
        <Button type="default" onClick={onCancel}>返回</Button>
      ]}
    >
      <Spin spinning={loading}>
        {renderContent()}
      </Spin>
    </Modal>
  );
};

export default DeviceDetail;
